package com.gin.no_gay_alliance.fragment.forum;

import android.view.View;

import androidx.recyclerview.widget.DividerItemDecoration;

import com.gin.no_gay_alliance.adpter.forum.ForumSubGroupAdapter;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.callback.Callback;
import com.gin.no_gay_alliance.database.manager.AccountManager;
import com.gin.no_gay_alliance.databinding.FragmentForumFavorBinding;
import com.gin.no_gay_alliance.fragment.base.BaseBindingFragment;
import com.gin.no_gay_alliance.viewmodel.EntrySubGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * 收藏版面分组
 */
public class ForumFavorFragment extends BaseBindingFragment<FragmentForumFavorBinding> implements Callback<List<EntrySubGroup>> {
    ForumSubGroupAdapter adapter;

    @Override
    public void onResume() {
        super.onResume();

        updateStatus();
        updateFavorForum();
    }

    /**
     * onCreateView 的后续操作
     */
    @Override
    protected void onCreateView() {
        adapter = new ForumSubGroupAdapter(new ArrayList<>(), requireActivity());
        b.recyclerView.setAdapter(adapter);
        b.recyclerView.addItemDecoration(new DividerItemDecoration(requireActivity(), DividerItemDecoration.VERTICAL));
        b.swipeRefreshLayout.setOnRefreshListener(() -> this.load(true));
    }

    /**
     * 更新登陆状态
     */
    public void updateStatus() {
        AccountManager accountManager = MyApplication.app.accountManager;
        if (accountManager.isLogged()) {
            b.tvWarning.setVisibility(View.GONE);
            b.recyclerView.setVisibility(View.VISIBLE);
        } else {
            b.tvWarning.setVisibility(View.VISIBLE);
            b.recyclerView.setVisibility(View.GONE);
        }
    }

    public void updateFavorForum() {
        if (MyApplication.app.accountManager.isLogged()) {
            load(false);
        }
    }

    /**
     * 请求成功回调
     *
     * @param data 数据
     */
    @Override
    public void onSuccess(List<EntrySubGroup> data) {
        ui(() -> {
            adapter.setData(data);
            b.swipeRefreshLayout.setRefreshing(false);
        });
    }

    /**
     * 请求之前执行的操作
     */
    @Override
    public void beforeRequest() {
        b.swipeRefreshLayout.setRefreshing(true);
    }

    private void load(boolean ignoreCache) {
        MyApplication.app.managerFactory.getFavorForumManager().get(ignoreCache, this);
    }
}